//
//  hx711.c
//  electronic_scale
//
//  Copyright © 2019 Cyber SmartCar Lab. All rights reserved.
//

#include "hx711.h"



//HX711初始化
void HX711Init(void)	
{ 
	GPIO_InitTypeDef GPIO_InitStructure; 
	RCC_APB2PeriphClockCmd(HX711_GPIO_RCC, ENABLE);	 //使能端口时钟 

	//SCK
	GPIO_InitStructure.GPIO_Pin = HX711_SCK;	  
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;  
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; 
	GPIO_Init(HX711_GPIO,&GPIO_InitStructure);
	HX711_SCK_L();

	//DOUT 
	GPIO_InitStructure.GPIO_Pin = HX711_DOUT;	
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; 	  
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;	 //IO口速度为50MHz 
	GPIO_Init(HX711_GPIO, &GPIO_InitStructure);
	HX711_DOUT_H();
}




//读HX711芯片输出的数据
unsigned long HX711Read(void)
{ 
	unsigned long val = 0; 
	unsigned char i = 0; 

	while(READ_HX711_DOUT()); //判断模块是否准备好
	HX711_DELAY_US(1);
	HX711_SCK_L(); //sck 拉低
	while(!READ_HX711_DOUT()); //再次判断是否准备好
	
	for(i=0;i<24;i++) 
	{ 
		HX711_DELAY_US(100);
		HX711_SCK_H();	   //SCK=1 
		val=val<<1;
		HX711_DELAY_US(1); 
		HX711_SCK_L();	   //SCK=0 
		if(READ_HX711_DOUT())   //DOUT=1,读入数据
		{
			++val; 
		}
		HX711_DELAY_US(1);
	} 
	HX711_SCK_H(); 
	val = val^0x800000; 
	HX711_DELAY_US(1);
	HX711_SCK_L(); 
	HX711_DELAY_US(1); 
	return val; 	
}

//读HX711芯片输出的数据的平均值
unsigned long HX711ReadAvg(int times)
{
	int i = 0;
	long temp = 0;
	for(i=0; i< times; ++i)
	{
		temp += HX711Read();
	}
	return (temp / times);
}



